import {Component, OnInit, Input} from '@angular/core';
import {Map} from 'ol';
import {HttpService} from '@kylin/http';
import {NzMessageService} from 'ng-zorro-antd';
import {FrontPageService} from '../front-page.service';
import {SignSelectorService} from './sign-selector/sign-selector.service';

@Component({
    selector: 'kylin-map-symbolization',
    templateUrl: './map-symbolization.component.html',
    styleUrls: ['./map-symbolization.component.less']
})
export class MapSymbolizationComponent implements OnInit {
    @Input() map: Map;

    @Input() set layerInfo(val) {
        if (val) {
            this.layerName = val.layerName;
            this.layerId = val.layerId;
            this.layerType = {4: 'point', 5: 'line', 6: 'polygon'}[val.layerType];
        }
    };

    layerType: 'point' | 'line' | 'polygon';
    defaultSignSrcMap: any;
    layerName: string;
    layerId: string;
    curProp: any;
    propList: any;
    propValList: any;
    propValListCopy = new Array<any>();
    valFilterVisible = false;
    selectedVal: any;
    signSelVisible: boolean;
    selectSigns = new Array<any>();
    setSignLoading: boolean;
    defaultSignPath: any;

    constructor(private http: HttpService, private message: NzMessageService, private frontPageSvc: FrontPageService, private signService: SignSelectorService) {
        this.defaultSignSrcMap = this.signService.defaultSignSrcMap;
    }

    ngOnInit() {
        this.getPropList();
        this.defaultSignPath = this.signService.cleanURL(this.defaultSignSrcMap[this.layerType]);
    }

    getPropList() {
        this.http.get(`/layersLayer/properties/${this.layerId}`, {}).then(rep => {
            if (rep.resp_code === '10000') {
                this.propList = rep.data;
                this.curProp = this.propList[0];
                this.getPropValList();
            } else {
                this.message.error('获取属性值数据失败' + rep.resp_msg);
            }
        })
    }

    getPropValList() {
        this.http.get('/layersLayer/getUniqueValue', {
            layerId: this.layerId,
            attr: this.curProp
        } as any).then(rep => {
            if (rep.resp_code === '10000') {
                // TODO 后台接口完善后，联调修改
                this.propValList = rep.data.map(item => {
                    return {
                        ...item,
                        value: item[this.curProp],
                        checked: false
                    }
                });
            } else {
                this.message.error('获取属性名称数据失败' + rep.resp_msg);
            }
        })
    }

    insertAllVals() {
        this.propValList.map(item => item.checked = true);
    }

    insertSomeVals() {
        Object.assign(this.propValList, this.propValListCopy);
        this.valFilterVisible = false;
    }

    openInsertSome() {
        this.valFilterVisible = true;
        this.propValListCopy = this.propValList.map(item => Object.assign({}, item));
    }

    cancelInsertSome() {
        this.valFilterVisible = false;
        this.propValListCopy = new Array<any>();
    }

    deleteAllVals() {
        this.propValList.map(item => item.checked = false);
    }

    deleteOneVals() {
        if (this.selectedVal) {
            this.selectedVal.checked = false;
        }
    }

    openSignSelector(type, evt, propertyValue?: any) {
        this.signSelVisible = true;
        if (type === 'one') {
            this.selectDone = (rst) => {
                const params = this.getParamsByLayerType(this.layerType, rst);
                let repeat = false;
                this.selectSigns.map((item, index) => { // 去重
                    if (propertyValue === item.propertyValue) {
                        this.selectSigns[index] = {
                            propertyName: this.curProp,
                            propertyValue: propertyValue,
                            ...params
                        };
                        repeat = true;
                    }
                    return item;
                });
                if (!repeat) {
                    this.selectSigns.push({
                        propertyName: this.curProp,
                        propertyValue: propertyValue,
                        ...params
                    });
                }
                this.signSelVisible = false;
                const img = evt.target;
                const svg = rst.selSignEmbedEle.nativeElement.getSVGDocument().querySelector('svg');
                img.src = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svg.outerHTML))); // 给图片对象写入base64编码的svg流
            };
        } else if (type === 'all') {
            this.selectDone = ((rst) => {
                const params = this.getParamsByLayerType(this.layerType, rst) as any;
                if (params.width) {
                    params.width = +params.width;
                }
                if (params.size) {
                    params.size = +params.size;
                }
                this.http.put(`/layersLayer/updateLayerStyle?layerId=${this.layerId}&updateType=1`, [params]).then(rep => {
                    if (rep.resp_code === '10000') {
                        this.signSelVisible = false;
                        this.frontPageSvc.$reloadLayers({
                            panel: '地图符号化',
                            layerId: this.layerId,
                            layerName: this.layerName
                        });
                        const img = evt.target;
                        const svg = rst.selSignEmbedEle.nativeElement.getSVGDocument().querySelector('svg');
                        img.src = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(svg.outerHTML))); // 给图片对象写入base64编码的svg流
                    }
                })
            }) as any
        }
    }

    getParamsByLayerType(layerType, rst) {
        let params = {};
        switch (this.layerType) {
            case 'line':
                params = {
                    color: rst.color,
                    width: rst.width,
                    ...rst.params
                };
                if (!rst.noNeedKey) {
                    params['wellKnownName'] = rst.key;
                }
                break;
                break;
            case 'polygon':
                params = {
                    color: rst.contentColor,
                    width: rst.strokeWidth,
                    outLineColor: rst.outLineColor,
                    opacity: rst.opacity,
                    ...rst.params
                };
                if (!rst.noNeedKey) {
                    params['wellKnownName'] = rst.key;
                }
                break;
            default:
            case 'point':
                params = {
                    wellKnownName: rst.key,
                    color: rst.color,
                    size: rst.size,
                    rotation: rst.rotation,
                };
        }
        return params;
    }

    setSignsByProp(hiddenSvgEmbed: any) {
        this.setSignLoading = true;
        const stylePropVals = this.selectSigns.map(sign => {
            return sign['propertyValue']
        });
        const defaultSign = this.signService.getDefaultSignInfo(this.layerType, hiddenSvgEmbed, this.signService[this.layerType + 'Signs'][0]);
        const needDefaultSignVals = new Array<any>();
        this.propValList.map(item => {
            if (item.checked && stylePropVals.indexOf(item.value) === -1) {
                const signItem = {
                    ...defaultSign,
                    propertyName: this.curProp,
                    propertyValue: item.value
                };
                if (signItem.width) {
                    signItem.width = +signItem.width;
                }
                if (signItem.size) {
                    signItem.size = +signItem.size;
                }
                needDefaultSignVals.push(signItem);
            }
        });
        this.selectSigns = this.selectSigns.concat(needDefaultSignVals);
        this.http.put(`/layersLayer/updateLayerStyle?layerId=${this.layerId}&updateType=1`, this.selectSigns).then(rep => {
            this.setSignLoading = false;
            if (rep.resp_code === '10000') {
                this.signSelVisible = false;
                this.frontPageSvc.$reloadLayers({panel: '地图符号化', layerId: this.layerId, layerName: this.layerName});
                this.selectSigns = new Array<any>();
            }
        })
    }

    selectDone = (rst) => {
    };
}
